package com.yy.main.app.web;

import com.github.pagehelper.PageInfo;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.collections.YYMapKits;
import com.yy.main.app.mapper.TRoleMapper;
import com.yy.main.app.mapper.TRolePermissionMapper;
import com.yy.main.app.mapper.TUserRoleMapper;
import com.yy.main.app.service.IRolePermissionService;
import com.yy.main.app.service.IRoleService;
import com.yy.main.app.service.IUserRoleService;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.TRole;
import com.yy.pojo.base.TRolePermissionExample;
import com.yy.pojo.base.TUser;
import com.yy.pojo.base.TUserRoleExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 角色前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017-08-22
 */
@Controller
@RequestMapping("/role")
@Api(value = "角色的controller", tags = {"角色的controller"})
public class RoleController extends CommonController {

    @Resource(name = "iRoleService")
    private IRoleService iRoleService;
    @Resource(name = "iUserRoleService")
    private IUserRoleService iUserRoleService;
    @Resource(name = "iRolePermissionService")
    private IRolePermissionService iRolePermissionService;
    @Autowired
    private TRoleMapper tRoleMapper;
    @Autowired
    private TUserRoleMapper tUserRoleMapper;
    @Autowired
    private TRolePermissionMapper tRolePermissionMapper;


    /**
     * <p>
     * 跳转到角色管理列表页面
     * </p>
     *
     * @param session {@link HttpSession}
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @RequestMapping(value = "/roleList", method = RequestMethod.GET)
    @HasPers(name = "role:manager")
    @ApiOperation(value = "跳转到角色管理列表页面", httpMethod = "GET", notes = "跳转到角色管理列表页面，需要拥有role:manager权限")
    public ModelAndView roleList(HttpSession session) {
        return goToPageByModelAndView("system/role/role_list", null, getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 加载后台管理，角色管理的数据表格
     * </p>
     *
     * @param page  当前页数
     * @param limit 每页显示记录数
     * @return {@link HashMap}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @RequestMapping(value = "/roleTable", method = RequestMethod.GET)
    @ApiOperation(value = "加载后台管理，角色管理的数据表格", httpMethod = "GET", notes = "加载后台管理，角色管理的数据表格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true),
            @ApiImplicitParam(name = "name", value = "角色名称")
    })
    public @ResponseBody
    Map<String, Object> roleTable(Integer page, Integer limit, String name) {
        PageInfo rPage = iRoleService.roleTable(page, limit, name);
        return super.pageToMap(rPage);
    }

    /**
     * <p>
     * 跳转到编辑角色的页面
     * </p>
     *
     * @param id 角色ID
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @ApiOperation(value = "跳转到编辑角色的页面", httpMethod = "GET", notes = "跳转到编辑角色的页面，需要拥有role:add,role:update权限")
    @RequestMapping(value = "/roleform/{id}", method = RequestMethod.GET)
    @HasPers(name = "role:add,role:update")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", access = "如果是增加，那么id必为-1")
    })
    public ModelAndView roleForm(@PathVariable("id") String id, HttpServletRequest request) {
        TUser user = getCurrentUser(request.getSession());
        // 如果是新增id肯定是-1
        TRole role = tRoleMapper.selectByPrimaryKey(id);
        if (null == role) {
            role = new TRole();
            role.setId("-1");
        }
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("role", role);
        return goToPageByModelAndView("system/role/role_form", param, user.getId());
    }

    /**
     * <p>
     * 保存角色信息
     * </p>
     *
     * @param role          角色实体
     * @param permissionIds 与role关联的权限的id字符串以豆号分隔
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @ApiOperation(value = "保存角色信息", httpMethod = "POST", notes = "增加或修改操作")
    @RequestMapping(value = "/saverole", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveRole(TRole role, String permissionIds) {
        return iRoleService.saverole(role, permissionIds);
    }

    /**
     * <p>
     * 删除角色
     * </p>
     *
     * @param id 角色ID
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月13日
     */
    @RequestMapping(value = "/delrole/{id}", method = RequestMethod.POST)
    @HasPers(name = "role:delete")
    @ApiOperation(value = "删除用户", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true, paramType = "path")
    })
    @ResponseBody
    public Map<String, Object> delrole(@PathVariable("id") String id) {
        Map<String, Object> map = YYMapKits.createHashMap();

        // 查看角色是否与用户关联
        TUserRoleExample example = new TUserRoleExample();
        example.createCriteria().andRole_idEqualTo(id);
        long c = tUserRoleMapper.countByExample(example);
        if (c > 0) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "要删除的角色与用户相关联，不可以删除!");
            return map;
        }

        // 判断角色是否与权限关联
        TRolePermissionExample example1 = new TRolePermissionExample();
        example1.createCriteria().andRole_idEqualTo(id);
        c = tRolePermissionMapper.countByExample(example1);

        if (c > 0) {
            map.put("success", Boolean.FALSE);
            map.put("msg", "要删除的角色与权限相关联，不可以删除!");
            return map;
        }

        // 如果上面两步都通过，那么正常删除之
        Integer b = tRoleMapper.deleteByPrimaryKey(id);
        if (b > 0) {
            map.put("success", Boolean.TRUE);
            map.put("msg", "删除成功!");
        } else {
            map.put("success", Boolean.FALSE);
            map.put("msg", "删除失败，请重试!");
        }
        return map;
    }

}
